package com.feiyue.learning.advance.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.Date;
import java.util.Scanner;

/**
 * UDP 客户端
 * @author  feiyue
 * @date  2020/4/18
 */
public class UDPClient {
    private static final int BUFFER_SIZE = 1024;

    public static void main(String[] args) throws IOException {
        new UDPClient().send();
    }

    private void send() throws IOException {

        // 获取 DatagramChannel 通道
        DatagramChannel dChannel = DatagramChannel.open();

        // 设置为非阻塞
        dChannel.configureBlocking(false);
        ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
        Scanner sc = new Scanner(System.in);
        System.out.println("UDP 客户端启动成功");
        System.out.println("请输入发送的内容：");

        while (sc.hasNext()) {
            String next = sc.next();
            buffer.put((new Date() + " >> " + next).getBytes());
            buffer.flip();
            dChannel.send(buffer, new InetSocketAddress("127.0.0.1", 80));

            buffer.clear();
        }

        dChannel.close();
    }
}
